package com.woniu.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {


    @Bean//转换格式
    public Jackson2JsonMessageConverter converter(){
        Jackson2JsonMessageConverter jackson2JsonMessageConverter=new Jackson2JsonMessageConverter();
        return jackson2JsonMessageConverter;
    }
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
      //  rabbitTemplate.setReturnCallback(returnCallback);

        rabbitTemplate.setMandatory(true); //消息没有被消费 强制return
        rabbitTemplate.setConnectionFactory(factory);
        rabbitTemplate.setMessageConverter(converter());
        return rabbitTemplate;

    }
    @Bean
    public Queue queue(){
        return new Queue("order-queue",true,false,false);
    }
    @Bean
    public TopicExchange exchange(){
        return new TopicExchange("order-exchange",true,false);
    }
    @Bean
    public Binding binding(){
        return  BindingBuilder.bind(queue()).to(exchange()).with("order.#");
    }

    @Bean
    public Queue payqueue(){
        Map params = new HashMap<>();
        params.put("x-message-ttl",1000*60*15);
        params.put("x-dead-letter-exchange","dlx-exchange");
        params.put("x-dead-letter-routing-key","dlq.queue");
        return new Queue("pay-queue",true,false,false,params);
    }
    @Bean
    public TopicExchange payexchange(){
        return new TopicExchange("pay-exchange",true,false);
    }
    @Bean
    public Binding payinding(){
        return BindingBuilder.bind(payqueue()).to(payexchange()).with("pay.#");
    }
    @Bean
    public Queue dlqqueue(){
        return new Queue("dlq-queue",true,false,false);
    }
    @Bean
    public TopicExchange dlqexchange(){
        return new TopicExchange("dlx-exchange",true,false);
    }
    @Bean
    public Binding dlqbinding(){
        return BindingBuilder.bind(dlqqueue()).to(dlqexchange()).with("dlq.#");
    }
}
